package com.hdx.server.controller.user;


import com.hdx.common.constant.MessageConstant;
import com.hdx.common.exception.AddressBookBusinessException;
import com.hdx.common.result.Result;
import com.hdx.model.entity.AddressBook;
import com.hdx.server.service.AddressBookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/user/addressBook")
@Api(tags = "C端地址簿接口")
public class AddressBookController {

    @Autowired
    private AddressBookService addressBookService;

    @GetMapping("/list")
    @ApiOperation("查询当前登录用户的所有地址信息")
    public Result<List<AddressBook>> getAllAddressBook(){
        List<AddressBook> addressBookList=addressBookService.getAllAddressBook();
        return Result.success(addressBookList);
    }


    @PostMapping
    @ApiOperation("新增地址")
    public Result save(@RequestBody AddressBook addressBook){
        addressBookService.save(addressBook);
        return Result.success();
    }

    @GetMapping("/{id}")
    @ApiOperation("根据id查询地址")
    public Result<AddressBook> getById(@PathVariable Long id){
        AddressBook addressBook=addressBookService.getById(id);
        return Result.success(addressBook);
    }

    @PutMapping
    @ApiOperation("根据id修改地址")
    public Result update(@RequestBody AddressBook addressBook) {
        addressBookService.update(addressBook);
        return Result.success();

    }

    @PutMapping("/default")
    @ApiOperation("设置默认地址")
    public Result setDefault(@RequestBody AddressBook addressBook) {
        addressBookService.setDefault(addressBook);
        return Result.success();
    }

    @DeleteMapping
    @ApiOperation("根据id删除地址")
    public Result deleteById(Long id) {
        addressBookService.deleteById(id);
        return Result.success();
    }

    @GetMapping("default")
    @ApiOperation("查询默认地址")
    public Result<List<AddressBook>> getDefault() {
        List<AddressBook> defaultAddressBookList=addressBookService.getDefault();

        if (defaultAddressBookList == null || defaultAddressBookList.size() > 1) {
            throw new AddressBookBusinessException(MessageConstant.UNKNOWN_ERROR);

        }

        return Result.success(defaultAddressBookList);
    }

    }

